package com.hz.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.hz.dao.UserDao;
import com.hz.pojo.User;
import com.hz.service.UserService;
import com.hz.utils.MassageJson;
import com.hz.utils.RedisUtil;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Calendar.*;
import static java.util.Calendar.MILLISECOND;
import static java.util.Calendar.MINUTE;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserDao userDao;


    @Override
    public MassageJson<String> out(String token) {

        redisUtil.del("userlogins:" + token);


        return new MassageJson<String>("200", "请求成功", null);


    }

    @Override
    public synchronized MassageJson findUserList() {

        List<User> listuser = userDao.findUserList();
        System.out.println(listuser.size());
        if (listuser != null) {

            return new MassageJson("200", "请求成功", listuser);
        }
        return new MassageJson("400", "请求失败", null);
    }

    @Override
    public MassageJson<Integer> insertUser(String userName, String password) {
        Integer integer = userDao.insertUser(userName, password);

        return new MassageJson<Integer>("200","请求成功",integer);
    }

    @SneakyThrows
    @Override
    public void daochu(HttpServletResponse response) {
        List<User> listuser = userDao.findUserList();
        System.out.println(JSONObject.toJSONString(listuser));
        response.setContentType("application/force-download;application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("demo", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("sheet0").doWrite(listuser);
//        //用io流来写入数据

    }

    @Override
    public void daoRu(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),User.class,new ExcelListener()).sheet().doRead();
    }

    @Override
    public void test() {

        Map<String, Date> weekTimeMap = this.getWeekTime(new Date());
        Date startDate = (Date)weekTimeMap.get("startDate");
        Date endDate = (Date)weekTimeMap.get("endDate");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(startDate)+"--------");
        System.out.println(format.format(endDate)+"--------");

    }


    @Override
    public MassageJson<User> findeUserByToken(String token) throws Exception {
        MassageJson<User> massageJson = null;
        synchronized (massageJson) {
            if (!StringUtils.isEmpty(token)) {

                System.out.println(token);
                String strToken = redisUtil.getStr("userlogins:" + token);

                User user = JSONObject.parseObject(strToken, User.class);

                System.out.println(strToken);
                if (!StringUtils.isEmpty(strToken)) {

                    return new MassageJson<User>("200", "请求成功", user);
                }
                return new MassageJson("400", "token不正确", null);
            }

        }

        return new MassageJson("400", "请传入token", null);
    }

    @Override
    public MassageJson<String> userLogin(String userName, String userPassword) throws Exception {

        User user = userDao.loginUser(userName, userPassword);
        MassageJson massageJson = null;

        if (user != null) {

            String uuid = UUID.randomUUID().toString().replaceAll("-", "") + "-" + user.getId();

            String token = "userlogins:" + uuid;

            String users = JSONObject.toJSONString(user);
            System.out.println(token);
            redisUtil.setStr(token, users);
            return new MassageJson<String>("200", "登录成功", uuid);
        }

        return new MassageJson<String>("400", "登录失败", null);
    }

    public static Map<String,Date> getWeekTime(Date date) {
        Map<String,Date> dateMap = new HashMap<>();
        Calendar calendar = getInstance();
        calendar.setFirstDayOfWeek(MONDAY);
        calendar.setTime(date);

        calendar.set(DAY_OF_WEEK, MONDAY);
        setMinTimeOfDay(calendar);
        dateMap.put("startDate",calendar.getTime());

        calendar.set(DAY_OF_WEEK, SUNDAY);
        setMaxTimeOfDay(calendar);
        dateMap.put("endDate",calendar.getTime());
        return dateMap;
    }

    public static void setMinTimeOfDay(Calendar calendar) {
        calendar.set(HOUR_OF_DAY, 0);
        calendar.set(SECOND, 0);
        calendar.set(MINUTE, 0);
        calendar.set(MILLISECOND, 0);
    }
    public static void setMaxTimeOfDay(Calendar calendar) {
        calendar.set(HOUR_OF_DAY, 23);
        calendar.set(SECOND, 59);
        calendar.set(MINUTE, 59);
        calendar.set(MILLISECOND, 999);
    }

    public static int typeConversion(double d){

        String s = String.valueOf(d);
        int i = s.indexOf(".");

        String substring = s.substring(0, i);
        return Integer.valueOf(substring) ;

    }

    public static void main(String[] args) {

        Map<String, Date> weekTime = getWeekTime(new Date());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        System.out.println(format.format(weekTime.get("startDate"))+"开始时间");
        System.out.println(format.format(weekTime.get("endDate"))+"结束时间");


    }

}
